import { FC, useEffect, useMemo, useState } from "react";
import Chart from "react-apexcharts";
import { ApexOptions } from "apexcharts";
import { useAPI } from "../../hooks/useAPI.ts";
import { DatePicker, Form } from "@arco-design/web-react";
import dayjs from "dayjs";
import { formatDuration } from "./ActivityListAndRecord.tsx";
import Button from "@mui/material/Button";
import ButtonGroup from "@mui/material/ButtonGroup";
import { createData, disableFutureDates } from "./ActivityReport.tsx";

const colors = {
  坐着: "#ff9900",
  "站立/走路": "#22a7f0",
  躺着: "#5ad45a",
  在厕所: "#e14b31",
  外出: "#0060ff",
  摔倒: "#c23728",
};

// @ts-ignore
export const ActivityChart: FC<{ userId: number | string | undefined }> = ({
  userId,
}) => {
  const [selectionMode, setSelectionMode] = useState("hour");
  const [dateRange, setDateRange] = useState([
    dayjs().subtract(1, "day").format("YYYY-MM-DD"), // Yesterday
    dayjs().subtract(1, "day").format("YYYY-MM-DD"), // Today
  ]);

  const [data, setData] = useState<any>(null);
  const [xAxis, setXAxis] = useState<string[]>([]);
  const [stackType] = useState<string>("100%");
  const api = useAPI();

  useEffect(() => {
    if (dateRange[0] === undefined) {
      dateRange[0] = dayjs().subtract(1, "day").format("YYYY-MM-DD");
      dateRange[1] = dayjs().subtract(1, "day").format("YYYY-MM-DD");
    }
    api
      .getElderReport(
        userId,
        `${dateRange[0].replace(/[-: ]/g, "_")}_00_00_00`,
        `${dateRange[1].replace(/[-: ]/g, "_")}_23_59_59`,
        selectionMode,
      )
      .then((response) => {
        const inputData = response.data.data;
        const uniqueActions = Array.from(
          new Set(
            inputData.flatMap((item: any) =>
              item.action.flatMap((action: any) => Object.keys(action)),
            ),
          ),
        );

        // Step 2: Create a mapping for each action and fill it with 0s for each hour slot
        const series = uniqueActions.map((action) => ({
          name: action,
          data: Array(inputData.length).fill(0), // Initialize with 0 for each hour slot
          color: colors[action as keyof typeof colors],
        }));

        // Step 3: Populate the data array with the actual durations from the JSON
        inputData.forEach((item: any, index: number) => {
          item.action.forEach((action: any) => {
            Object.entries(action).forEach(([actionName, duration]) => {
              const actionSeries = series.find(
                (ser) => ser.name === actionName,
              );
              if (actionSeries) {
                actionSeries.data[index] = duration;
              }
            });
          });
        });

        // Step 4: Get the table format
        const tableData = inputData.map((item: any, index: number) => {
          // Check if there is any "摔倒" action
          return createData(
            index + 1,
            item.hour,
            item.status,
            item.remark[1],
            item.remark[2],
            item.event,
          );
        });
        setXAxis(tableData.map((item: any) => item.time));
        setData(series);
      });
  }, [dateRange]);

  const chartOptions = useMemo<ApexOptions>(
    () => ({
      chart: {
        type: "bar",
        height: 500,
        stacked: true,
        stackType: "100%",
        toolbar: { show: true },
        zoom: {
          autoScaleYaxis: true,
        },
        defaultLocale: "cn",
        locales: [
          {
            name: "cn",
            options: {
              toolbar: {
                selection: "选择",
                selectionZoom: "放大已选",
                zoomIn: "放大",
                zoomOut: "缩小",
                pan: "拖拽",
                reset: "重置",
              },
            },
          },
        ],
      },
      stroke: {
        width: 1,
        colors: ["#fff"],
      },
      title: {
        text: "住户每日行动时间分布",
        align: "center",
        style: {
          color: "#121212",
          fontSize: "16px",
        },
      },
      noData: {
        text: "暂无数据",
      },
      grid: {
        padding: {
          left: 0,
          right: 0,
        },
        yaxis: {
          lines: { show: false },
        },
        row: {
          colors: ["#fff", "#f2f2f2"],
        },
      },
      xaxis: {
        categories: xAxis,
        tickPlacement: "on",
        title: {
          // text: "小时数/h",
          offsetX: 0,
          offsetY: 0,
          style: {
            color: undefined,
            fontSize: "12px",
            fontWeight: 600,
            cssClass: "apexcharts-yaxis-title",
          },
        },
        labels: {
          style: {
            colors: "#121212",
          },
          formatter: function (value: any) {
            value = value?.split(" ");
            if (value?.length == 2) return `${value[1]}点`;
            else return value;
          },
        },
      },
      yaxis: {
        labels: {
          offsetX: -20,
          style: {
            colors: "#121212",
          },
          formatter: function (value: any) {
            return `${value}%`; // Format the labels to append %
          },
        },
        title: {
          text: "时间分配",
          rotate: 0,
          offsetX: 30,
          offsetY: -160,
          style: {
            color: undefined,
            fontSize: "12px",
            fontWeight: 600,
            cssClass: "apexcharts-yaxis-title",
          },
        },
      },
      tooltip: {
        y: {
          formatter(val: any) {
            return `${formatDuration(Math.ceil(val))}`;
          },
        },
      },
      fill: {
        type: "gradient",
        gradient: {
          shade: "light",
          type: "horizontal",
          shadeIntensity: 0.1,
          gradientToColors: undefined,
          inverseColors: true,
          opacityFrom: 0.85,
          opacityTo: 0.85,
          stops: [50, 0, 100],
        },
      },
      plotOptions: {
        bar: {
          borderRadius: 3,
          borderRadiusWhenStacked: "all",
          borderRadiusApplication: "around",
        },
      },
      legend: {
        position: "top",
        horizontalAlign: "right",
        offsetX: 40,
        fontFamily: "Poppins, sans-serif",
        itemMargin: {
          vertical: 5,
          horizontal: 15,
        },
      },
      dataLabels: {
        enabled: false,
      },
    }),
    [stackType, xAxis, data],
  );

  // @ts-ignore
  return (
    data && (
      <>
        <Form layout={"inline"}>
          <Form.Item label="模式：" field="key" style={{ marginLeft: "10px" }}>
            <ButtonGroup aria-label="Basic button group">
              <Button
                variant={selectionMode === "hour" ? "contained" : "outlined"}
                onClick={() => {
                  setSelectionMode("hour");
                  setDateRange([
                    dayjs().subtract(8, "day").format("YYYY-MM-DD"), // Yesterday
                    dayjs().subtract(8, "day").format("YYYY-MM-DD"), // Yesterday
                  ]);
                  // setRefresh(!refresh)
                }}
              >
                按天
              </Button>
              <Button
                variant={selectionMode === "day" ? "contained" : "outlined"}
                onClick={() => {
                  setSelectionMode("day");
                  setDateRange([
                    dayjs().subtract(8, "day").format("YYYY-MM-DD"), // Yesterday
                    dayjs().subtract(1, "day").format("YYYY-MM-DD"), // Today
                  ]);
                  // setRefresh(!refresh)
                }}
              >
                近七天
              </Button>
              <Button
                variant={selectionMode === "week" ? "contained" : "outlined"}
                onClick={() => {
                  setSelectionMode("day");
                  setDateRange([
                    dayjs().subtract(30, "day").format("YYYY-MM-DD"), // Yesterday
                    dayjs().subtract(1, "day").format("YYYY-MM-DD"), // Today
                  ]);
                  // setRefresh(!refresh)
                }}
              >
                近三十天
              </Button>
            </ButtonGroup>
          </Form.Item>
          <Form.Item>
            {selectionMode === "hour" ? (
              <DatePicker
                onChange={(date) => setDateRange([date, date])}
                style={{ width: "250px" }}
                value={dateRange[0]}
                disabledDate={disableFutureDates}
                placeholder="请选择日期"
              />
            ) : null}
          </Form.Item>
        </Form>
        <Chart
          style={{ marginTop: "20px" }}
          height={400}
          series={data}
          type={"bar"}
          options={chartOptions}
        />
      </>
    )
  );
};
